package com.tarena.lbs.business.servcie.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.constant.BusinessTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.servcie.BusinessService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessRepository businessRepository;
    @DubboReference
    private AttachApi attachApi;
    @DubboReference
    private UserApi userApi;

    @Override
    public PageResult<BusinessVO> SelectPageList(BusinessQuery query) {
        log.info("查询商家列表，入参:{}",query);
        PageResult<BusinessVO> result = new PageResult<>();
        PageInfo<BusinessPO> pageInfo = businessRepository.SelectPageList(query);
        result.setPageNo(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());
        List<BusinessVO> vos = null;
        List<BusinessPO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                BusinessVO vo = new BusinessVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        result.setObjects(vos);
        log.info("查询商家列表，出参:{}",result);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(BusinessParam param){
        log.info("保存商家信息，入参:{}",param);
        Roles role = AuthenticationContextUtils.get().getRole();
        if (role==Roles.ADMIN){
            BusinessQuery query = new BusinessQuery();
            query.setBusinessName(param.getBusinessName());
            PageInfo<BusinessPO> result = businessRepository.SelectPageList(query);
            if (result.getTotal()==0L){
                BusinessPO po = new BusinessPO();
                BeanUtils.copyProperties(param,po);
                po.setEntryTime(new Date());
                businessRepository.save(po);
                Integer businessId = po.getId();
                bindPictures(businessId,param);
            }
            else {
                throw new RuntimeException("名字重复");
            }
        }else {
            throw new RuntimeException("权限不足");
        }
    }

    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) {
        log.info("商家详情，入参:{}",businessId);
        BusinessPO businessPO = businessRepository.findById(businessId);
        BusinessStoreVO result = new BusinessStoreVO();
        if (businessPO!=null){
            BeanUtils.copyProperties(businessPO,result);
            result.setStoreVOList(null);
        }else {
            throw new RuntimeException("商家不存在");
        }
        log.info("商家详情，出参:{}",result);
        return result;
    }

    @Override
    public void updateStatus(BusinessParam param) {
        log.info("更新商家状态，入参:{}",param);
        BusinessPO po = businessRepository.findById(param.getId());
        if (po!=null){
            po.setBusinessStatus(param.getBusinessStatus());
            po.setAuditRemarks(param.getAuditRemarks());
            businessRepository.updateStatusById(po);
        }
    }

    @Override
    public void exportAllBusiness(HttpServletResponse response) throws Exception {
        log.info("开始导出全部商家数据");

        // 查询所有商家数据（不分页）
        BusinessQuery query = new BusinessQuery();
        query.setPageSize(Integer.MAX_VALUE); // 设置最大页数获取所有数据
        PageInfo<BusinessPO> pageInfo = businessRepository.SelectPageList(query);
        List<BusinessPO> businessList = pageInfo.getList();

        log.info("导出商家数据数量: {}", businessList.size());

        if (CollectionUtils.isEmpty(businessList)) {
            throw new Exception("没有商家数据可导出");
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("全部商家数据_" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 创建Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("商家数据");

            // 创建表头样式
            CellStyle headerStyle = createHeaderStyle(workbook);

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "商家名称", "行业类型", "负责人", "联系电话", "公司地址", "商家状态", "入驻时间", "审核备注"};

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                // 设置列宽
                sheet.setColumnWidth(i, 20 * 256);
            }

            // 创建数据样式
            CellStyle dataStyle = createDataStyle(workbook);

            // 填充数据
            int rowNum = 1;
            for (BusinessPO business : businessList) {
                Row row = sheet.createRow(rowNum++);

                // ID
                createCell(row, 0, business.getId() != null ? business.getId().toString() : "", dataStyle);

                // 商家名称
                createCell(row, 1, business.getBusinessName(), dataStyle);

                // 行业类型 - 这里需要根据实际情况获取行业名称
                createCell(row, 2, getIndustryName(business.getIndustryType()), dataStyle);

                // 负责人
                createCell(row, 3, business.getBusinessHeadName(), dataStyle);

                // 联系电话
                createCell(row, 4, business.getBusinessHeadPhone(), dataStyle);

                // 公司地址
                createCell(row, 5, business.getCompanyAddress(), dataStyle);

                // 商家状态
                createCell(row, 6, getBusinessStatusText(business.getBusinessStatus()), dataStyle);

                // 入驻时间
                createCell(row, 7, formatDateTime(business.getEntryTime()), dataStyle);

                // 审核备注
                createCell(row, 8, business.getAuditRemarks(), dataStyle);
            }

            // 写入响应流
            workbook.write(response.getOutputStream());
            log.info("商家数据导出成功，共导出{}条记录", businessList.size());
        } catch (Exception e) {
            log.error("Excel写入失败", e);
            throw new Exception("Excel文件生成失败");
        }
    }

    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    private CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);
        return style;
    }

    private void createCell(Row row, int column, String value, CellStyle style) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value != null ? value : "");
        cell.setCellStyle(style);
    }

    private String getBusinessStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "待审核";
            case 2: return "已通过";
            case 3: return "已驳回";
            default: return "未知";
        }
    }

    private String formatDateTime(Date date) {
        if (date == null) return "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    private String getIndustryName(Integer industryType) {
        if (industryType == null) return "未知行业";
        // 这里需要根据实际的行业类型映射来返回行业名称
        // 您可以根据业务需求修改这个映射关系
        switch (industryType) {
            case 1: return "餐饮美食";
            case 2: return "零售百货";
            case 3: return "生活服务";
            case 4: return "教育培训";
            default: return "其他行业";
        }
    }

    private void bindPictures(Integer businessId, BusinessParam param){
        List<PicUpdateParam> picParams=new ArrayList<>();
        PicUpdateParam licenseParam=new PicUpdateParam();
        licenseParam.setBusinessType(BusinessTypes.BIZ_LICENSE);
        licenseParam.setBusinessId(businessId);
        String licenseUrl = param.getBusinessLicense();
        PicUpdateParam logoParam=new PicUpdateParam();
        logoParam.setBusinessType(BusinessTypes.BIZ_LOGO);
        logoParam.setBusinessId(businessId);
        String logoUrl = param.getBusinessLogo();
        picParams.add(licenseParam);
        picParams.add(logoParam);
        boolean result = attachApi.batchUpdateBusiness(picParams);
    }
}